Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Encapsulation in java

Getters and Setters

What are Getter and Setter Methods?

Getter and Setter methods, also known as Accessors and Mutators respectively, are used to protect your data, particularly when creating classes. They are integral components in Java for managing class attributes or fields.

Getter Methods (Accessors)

Getter methods, also known as accessors, are methods that allow you to retrieve the value of an object’s private instance variables. These methods provide read-only access to the object’s state. By using accessor methods, you can ensure that the object’s state is not modified accidentally or maliciously by external code.

Setter Methods (Mutators)

Setter methods, also known as mutators, are methods that allow you to modify the value of an object’s private instance variables. These methods provide write-only access to the object’s state. By using mutator methods, you can ensure that the object’s state is modified only through a controlled interface. Example of Getter and Setter Methods in Java Here’s an example of getter and setter methods in Java:
Encapsulation getter and setter example in java class Person { private String name; private int age; private String email; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } } public class Main{ public static void main(String[] args){ Person obj=new Person(); obj.setName("John"); obj.setAge(23); obj.setEmail("john@tutorialsbox.com"); System.out.println(obj.getName() + "\n" + obj.getAge() + "\n" + obj.getEmail()); } }

Output

John 23 john@tutorialsbox.com
In this example, we have defined three accessor methods: getName(), getAge(), and getEmail(), and three mutator methods: setName(), setAge(), and setEmail(). The accessor methods return the value of the corresponding instance variable, while the mutator methods set the value of the corresponding instance variable.

Advantages of Getter and Setter Methods

✦ Getters and setters let you manage how crucial variables in your code are accessed and altered. ✦ They give you the convenience of entering the value of the variables of any data type by the requirement of the code. ✦ They make the programmer convenient in setting and getting the value for a particular data type. Remember, getter and setter methods are an essential part of encapsulation in Java. They allow you to control access to an object’s state, ensuring that it is accessed and modified only through a controlled interface.

  📌TAGS

★Class ★ Method ★ Object ★ java ★ oops ★Encapsulation ★ Getter and Setter

Tutorials